// pages/yoshop/article/index.js

let _this;
let common = require('../../utils/common.js');
let Bmob = require('../../utils/bmob.js');
let App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollViewHeight: 0,
    isJoined: true,
    hideMask: true,
    currentVideoUrl: '',
    currentResourceId: '',
    currentStudyResourceId: '',
    currentStudyResourceStatus: '',
    recordTime: 0,
    timeCount: 0,
    durationOfStudy: 0,
    currentJoinCourseId: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    _this = this;
    Bmob.initialize("8bbd2fa87eece23337234b59c300fb2e", "0422786c4a1502011b37da0d9f437770")

    _this.data.id = options.id;
    _this.videoContext = wx.createVideoContext('resourceVideo', this)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    wx.showLoading({
      title: '获取数据中...',
    })

    wx.setNavigationBarTitle({
      title: '课程',
    })

    _this.setScrollViewHeight()
    _this.getArticle()
    _this.getResources()
    _this.getDurationOfStudy()
    _this.isJoined()

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    console.log('上传时长 from onHide')
    _this.putDurationOfStudy(Math.floor(_this.data.timeCount / 240))
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    console.log('上传时长 from onUnload')
    _this.putDurationOfStudy(Math.floor(_this.data.timeCount / 240))
  },

  /**
   * 获取课程基本信息
   */
  getArticle: function() {
    let _urlArticle = 'classes/Article' + '/' + _this.data.id;
    App._get(_urlArticle, {}, function(res) {
      console.log(res)
      _this.setData({
        article: res
      })
    })
  },

  /**
   * 获取课程资源
   */
  getResources: function() {
    let _urlResource = 'classes/Resource?where={"article":"' + _this.data.id + '"}'
    App._get(_urlResource, {}, function(res) {
      wx.hideLoading()
      console.log(res)
      _this.setData({
        resources: res.results
      })

      _this.getStudyResource()

    })
  },

  /**
   * 获取资源学习记录
   */
  getStudyResource: function() {

    let resourceIds = []
    for (var i = 0; i < _this.data.resources.length; ++i) {
      resourceIds.push(_this.data.resources[i].objectId)
    }
    console.log(resourceIds)

    let _url = 'classes/StudyResource?where={"user":"Wbm0HHHR", "resource":{"$in":' + JSON.stringify(resourceIds) + '}}'

    App._get(_url, {}, function(res) {
      _this.setData({
        studyResources: res.results
      })
      console.log(res.results)
    })
  },

  /**
   * 检查是否已加入学习
   */
  isJoined: function() {
    let _urlJoin = 'classes/JoinCourse?where={"article":"' + _this.data.id + '", "user":"' + wx.getStorageSync('bmobObjectId') + '"}'
    //console.log(_urlJoin)
    App._get(_urlJoin, {}, function(res) {
      if (res.results.length > 0) {
        _this.setData({
          isJoined: true,
          currentJoinCourseId: res.results[0].objectId
        })
      } else {
        _this.setData({
          isJoined: false
        }, function() {
          _this.setScrollViewHeight()
        })
      }

    })
  },

  /**
   * 加入学习
   */
  join: function() {
    if (wx.getStorageSync('userName')) {
      wx.showToast({
        title: '加入成功',
        duration: 1000
      })

      let bmobObjectId = wx.getStorageSync('bmobObjectId')
      console.log(bmobObjectId + '已加入')

      wx.showLoading({
        title: '数据处理中...',
      })

      let _url = 'classes/JoinCourse'
      App._post(_url, {
        "user": {
          "__type": "Pointer",
          "className": "_User",
          "objectId": bmobObjectId
        },
        'article': {
          "__type": "Pointer",
          "className": "Article",
          "objectId": _this.data.id
        },
        'completedResTotal': 0
      }, function(res) {
        wx.hideLoading()
        wx.showToast({
          title: '加入成功',
        })
        console.log(res)
        _this.isJoined()
      })

    } else {
      wx.switchTab({
        url: '../login',
      })
    }
  },

  /**
   * 播放资源
   */
  playResource: function(e) {
    if (_this.data.isJoined) {

      let _index = e.currentTarget.dataset.resourceindex
      let _resource = _this.data.resources[_index]

      //播放视频资源
      if (_resource.category === 'video') {
        console.log('播放视频' + _resource.videoUrl)
        _this.setData({
          hideMask: false,
          currentVideoUrl: _resource.videoUrl,
          currentResourceId: _resource.objectId
        })

        _this.checkStudyResource(_resource.objectId)

      }

    } else {
      wx.showToast({
        icon: 'none',
        title: '请先加入课程',
      })
    }

  },

  /**
   * 关闭遮罩层
   */
  closeMask: function() {
    _this.videoContext.pause()

    var _amount = Math.floor(_this.data.timeCount / 240)
    if (_amount > 0) {
      console.log('上传时长 from closeMask')
      _this.putDurationOfStudy(_amount)
    }
    _this.setData({
      hideMask: true
    })
  },

  /**
   * 视频播放事件
   */
  onPlay: function(e) {
    //console.log(e)
  },

  /**
   * 时间更新事件
   */
  onTimeUpdate: function(e) {
    //记录当前时间并计数器加1
    let _count = _this.data.timeCount
    _count++

    _this.setData({
      recordTime: e.detail.currentTime,
      timeCount: _count
    })

    //当合计5分钟时上传数据
    _this.checkTimeCounter(_count, e)

  },

  /**
   * 播放结束事件
   */
  onEnded: function() {

    if (_this.data.currentStudyResourceStatus !== 'completed') {
      _this.putStatus()
    }
  },

  /**
   * 检查计数器是否达标
   */
  checkTimeCounter: function(count, event) {
    if (count === 1200) {

      console.log(event.detail)
      console.log('上传学习时长')
      _this.putDurationOfStudy(5)
    }
  },

  /**
   * 获取当前的总学习时长
   */
  getDurationOfStudy: function() {
    let _url = 'classes/Profile/' + wx.getStorageSync('profileId')

    App._get(_url, {}, function(res) {
      _this.setData({
        durationOfStudy: res.durationOfStudy
      })
    })
  },

  /**
   * 检查资源学习记录
   */
  checkStudyResource: function(resourceId) {
    console.log('checkStudyResource')
    console.log(resourceId)
    console.log(_this.data.studyResources)

    let isExists = _this.data.studyResources.some(function(val, index, arr) {
      console.log(val)
      if (val.resource.objectId === resourceId) {
        _this.setData({
          currentStudyResourceId: val.objectId,
          currentStudyResourceStatus: val.status
        })
        return true
      } else {
        return false
      }
    })

    console.log(isExists)

    //如果学习记录不存在则创建记录
    if (!isExists) {
      _this.createStudyResource()
    }
  },

  /**
   * 创建资源学习记录
   */
  createStudyResource: function() {
    let _url = 'classes/StudyResource'

    App._post(_url, {
      "user": {
        "__type": "Pointer",
        "className": "_User",
        "objectId": wx.getStorageSync('bmobObjectId')
      },
      'resource': {
        "__type": "Pointer",
        "className": "Resource",
        "objectId": _this.data.currentResourceId
      },
      'status': 'start',
      'lastTime': 0
    }, function(res) {
      console.log(res)
      //更新当前学习记录Id
      _this.setData({
        currentStudyResourceId: res.objectId
      })
      //同步学习资源数组
      _this.getStudyResource()

      let _urlResource = 'classes/Resource/' + _this.data.currentResourceId
      App._put(_urlResource, '', {

        "studyResource": {

          "__op": "AddRelation",
          "objects": [{
            "__type": "Pointer",
            "className": "StudyResource",
            "objectId": res.objectId
          }]
        }

      }, function(res) {
        console.log(res)
      })
    })
  },

  /**
   * 更新学习时长
   */
  putDurationOfStudy: function(amount) {

    if (amount > 0) {
      let _url = 'classes/Profile/' + wx.getStorageSync('profileId')

      App._put(_url, '', {
        'durationOfStudy': {
          '__op': 'Increment',
          'amount': amount
        }
      }, function(res) {
        console.log('学习时长+' + amount)
        console.log('计数器清零')
        _this.setData({
          timeCount: 0
        })
      })
    }
  },

  /**
   * 更新资源学习状态
   */
  putStatus: function() {
    let _urlStudyResource = 'classes/StudyResource/' + _this.data.currentStudyResourceId
    App._put(_urlStudyResource, '', {
      'status': 'completed'
    }, function(res) {
      console.log('记录学习完成')
    })

    let _urlJoinCourse = 'classes/JoinCourse/' + _this.data.currentJoinCourseId
    App._put(_urlJoinCourse, '', {
      'completedResTotal': {
        '__op': 'Increment',
        'amount': 1
      }
    }, function(res) {
      console.log('完成资源数+1')
    })
  },

  /**
   * 更新资源最近学习结束时间点
   */
  putLastTime: function() {},

  /**
   * 设置ScrollView高度
   */
  setScrollViewHeight: function() {
    const query = wx.createSelectorQuery()
    let _heightFooter
    query.select('#footer').boundingClientRect()
    query.exec(function(res) {
      _heightFooter = res[0].height
      _this.setData({
        scrollViewHeight: common.getScrollViewHeight(0, _heightFooter)
      })
    })
  }
})